package com.cloud.client2.cloudclient2;

import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@RestController
@EnableEurekaClient
public class Cloudclient2Application {

	@Autowired
	private EurekaClient eurekaClient;

	@Autowired
	RestTemplateBuilder restTemplateBuilder;

	@Bean
	public RestTemplate getRestTemplate(){
		return restTemplateBuilder.build();
	}

	@Autowired
	private RestTemplate restTemplate;

	public static void main(String[] args) {

		SpringApplication.run(Cloudclient2Application.class, args);
	}

	@Value("${server.port}")
	String port;
	@RequestMapping("/")
	public String home() throws  Exception{
		Thread.sleep(2000);
		return "hello world from port " + port;
	}
	@RequestMapping(value = "/getServer",method = RequestMethod.GET)
	private String getCloudServer(){
		InstanceInfo nextServerFromEureka = eurekaClient.getNextServerFromEureka("client1-service", false);
		return restTemplate.getForObject(nextServerFromEureka.getHomePageUrl()+"/client",String.class);
	}

}
